import React, { useState, memo, useEffect, useCallback } from 'react';
import { Table, Button, Row, Col } from 'tdesign-react';
import { getPackageInfoListApi } from 'api/user';
import classnames from 'classnames';
import CommonStyle from 'styles/common.module.less';
import useLoading from 'hooks/useLoading';
import { createColumns } from 'utils/tableUtils';
import { ALL_SOURCE_OPTIONS, CHANNEL_PROMOTION_MAP, PLATFORM_OPTIONS, PROMOTION_MAP, USER_TYPE_MAP, USER_TYPE_OPTIONS } from 'constants/index';
import SakuraSearchForm from 'components/SakuraSearchForm';
import IppeakTable from 'components/IppeakTable';
import { createRequestParams } from 'utils';
import { handleSource, SOURCE_OPTIONS, USER_STATUS_OPTIONS } from '../baseInfo/consts';

// 初始查询参数
const INITIAL_QUERY = {
  page: 1,
  page_size: 10,
};

// 初始表格状态
const INITIAL_TABLE_STATE = {
  list: [],
  total: 0,
  current: 1,
  pageSize: 10,
};

export const SelectTable = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([0, 1]);
  const [visible, setVisible] = useState(false);
  const { loading, setLoading } = useLoading(false);

  // 表格状态管理
  const [table, setTable] = useState(INITIAL_TABLE_STATE);
  const [query, setQuery] = useState<any>(INITIAL_QUERY);
  const [hideQuerys, sethideQuerys] = useState<{ qudao: boolean; tuiguang: boolean }>({
    qudao: true,
    tuiguang: true,
  });
  const { list, total, current, pageSize } = table;
  const clearFieldAtDate = (value: string) => {
    if(!value.length){
      delete query.start_time
      delete query.end_time
      setQuery((pre: any) => ({
        ...pre,
        page:1,
        page_size:pre.page_size || 10
      }))
    }
  }
  // 表格列定义
  const columns = createColumns([
    {
      label: '用户ID',
      align: 'left',
      key: 'user_id',
      
    },
    {
      label: '邮箱',
      key: 'username',
      width: 220,
    },
    {
      label: '用户类型',
      key: 'tags',
      render({ row }: any) {
        const tagColor = row.tags === 'vip' ? '#7868e6' : row.tags === 'staff' ? '#f80' : 'inherit';
        return <span style={{ color: tagColor, cursor: 'pointer' }}>{USER_TYPE_MAP[row.tags] || '-'}</span>;
      },
    },
    {
      label: '已购流量',
      key: 'purchased_flow',
    },
    {
      label: '可用流量',
      key: 'use_flow',
      defaultValue: '0 KB',
    },
    {
      label: '冻结流量',
      key: 'freeze_flow',
      defaultValue: '0 KB',
    },
    {
      label: '流量到期时间',
      key: 'expire_flow',
      width: '180',
      type: 'date',
    },
    {
      label: '不限量购买天数',
      key: 'purchased_unlimited_day',
      width: '140',
    },
    {
      label: '不限量可用天数',
      key: 'use_unlimited_day',
      width: '140',
    },
    {
      label: '不限量到期时间',
      key: 'unlimited_expire',
      type: 'date',
    },
    {
      label: '已购静态数量',
      key: 'purchased_static_count',
      width: '140',
    },
    {
      label: '可用静态数量',
      key: 'use_static_count',
      width: '140',
    },
    {
      label: '过期静态数量',
      key: 'expired_static_count',
      width: '140',
    },
    {
      label: '钱包余额',
      key: 'balance',
    },
    {
      label: '累计充值',
      key: 'recharge_count',
    },
    {
      label: '累计返利',
      key: 'rebate_count',
    },
    {
      label: '累计消费',
      key: 'consume_count',
    },
    {
      label: '注册时间',
      key: 'register_time',
      type: 'date',
    },
  ]);

   // 表单字段定义
   const formFields: any[] = [
    {
      label: '用户ID',
      name: 'uid',
      type: 'input',
      onChange: (value: any) => {
        if (value == null || String(value).trim() === '') {
          setQuery((prev: any) => {
            const { uid, ...rest } = prev || {};
            return { ...rest };
          });
        }
      },
      colWrap: {
        colSpan: 2.5,
        labelWidth: 60,
        width: 86,
      },
    },
    {
      label: '邮箱',
      name: 'username',
      type: 'input',
     
      colWrap: {
        colSpan: 2.5,
        labelWidth: 50,
        width: 156,

      },
    },
    {
      label: '用户类型',
      name: 'tags',
      type: 'select',
      options: USER_TYPE_OPTIONS,
    },
    {
      label: '用户状态',
      name: 'status',
      type: 'select',
      options: USER_STATUS_OPTIONS
    },
    {
      label: '来源',
      type: 'select',
      name:'a_source',
      options: SOURCE_OPTIONS,
      colWrap: {
        colSpan: 1.5,
        labelWidth: 50,
      },
      onChange: (value: any) => { handleSource(value) }
    },
    {
      label: '渠道名称',
      name: 'channel_name',
      type: 'input',
     
      hide: hideQuerys.qudao,
    },
    {
      label: '推广系列',
      name: 'series',
      type: 'input',
     
      hide: hideQuerys.tuiguang,
    },
    {
      label: '注册时间',
      name: 'register_time',
      type: 'date',
      returnType:'timestamp',
      onChange:clearFieldAtDate
    },
  ];
  
  useEffect(()=>{
    if(!query.a_source){
      delete query?.origin
      delete query?.channel
      delete query?.source
      delete query?.channel_name
      delete query?.series
    }
  }, [query.a_source]);
    const handleSource =(value: string)=>{
    let platforms = PLATFORM_OPTIONS.map(item=>(item.label))
    let promotions = PROMOTION_MAP.map(item=>(item.label)) // 推广
    let biddings =  CHANNEL_PROMOTION_MAP.map(item=>(item.label)) // 渠道
    if(promotions.includes(value)){
      sethideQuerys((pre: { qudao: boolean; tuiguang: boolean }) => ({...pre,tuiguang:false,qudao:true}))
    }else if(biddings.includes(value)){
      sethideQuerys((pre: { qudao: boolean; tuiguang: boolean }) => ({...pre,qudao:false,tuiguang:true}))
    }else{
      sethideQuerys((pre: { qudao: boolean; tuiguang: boolean }) => ({
        ...pre,
        qudao: true,
        tuiguang: true,
      }))
    }

  }

    // 统一的字段清除处理函数
    const handleFieldClear = (fieldName: string) => {
      setQuery((prev: any) => {
        const { [fieldName]: removed, ...rest } = prev || {};
        return { ...rest, };
      });
    };

  // 获取用户列表数据
  const fetchUserList = useCallback(
    async (params?: any) => {
      setLoading(true);
      try {
        // 合并参数并过滤空值，query 优先级更高
        delete query?.register_time
        const requestParams = createRequestParams({ ...query, ...params });
        console.log('API 请求参数:', requestParams);
        const res: any = await getPackageInfoListApi(requestParams);
        setLoading(false);
        setTable((pre: any) => ({
          ...pre,
          list: res.results || [],
          total: res.total || 0,
        }));
      } catch (err) {
        console.log(err, 'err');
        setLoading(false);
      }
    },
    [query],
  );

  // 处理选择变化
  const onSelectChange = useCallback((value: (string | number)[]) => {
    setSelectedRowKeys(value);
  }, []);

  const handleSearch = useCallback((values: any) => {
    let platforms = PLATFORM_OPTIONS.map(item=>(item.label))
    let promotions = PROMOTION_MAP.map(item=>(item.label)) // 推广
    let biddings =  CHANNEL_PROMOTION_MAP.map(item=>(item.label)) // 渠道
    let type = ''
    if(values.a_source == 1||values.a_source==2){
      type='origin'
    }else if(promotions.includes(values.a_source)){
        type='source'
        delete values.channel_name
    }else if(biddings.includes(values.a_source)){
      type='channel'
      delete values.series
    }
    const startTime = values?.register_time?.[0] || '';
    const endTime = values?.register_time?.[1] || '';
    const query = {
      ...values,
      [type]:values.a_source,
      start_time: startTime,
      end_time: endTime,
    }
    setQuery((pre: any)=>({
        ...query,
        page:1,
        page_size:10
    }))
  }, []);
  
  const handleReset = () => {
    setQuery(pre=>({
      page:1,
      page_size:10
    }));
  }

  const handlePaginationChange = useCallback((page: number, pageSize: number) => {
    setQuery((pre) => ({
      ...pre,
      page,
      page_size: pageSize,
    }));
  }, []);

  // 处理当前页变化
  const handleCurrentChange = useCallback(
    (current: number, pageInfo: any) => {
      handlePaginationChange(pageInfo.current, query.page_size);
    },
    [query.page_size, handlePaginationChange],
  );

  // 处理每页条数变化
  const handlePageSizeChange = useCallback(
    (size: number) => {
      handlePaginationChange(1, size); // 切换每页条数时重置到第一页
    },
    [handlePaginationChange],
  );

  // 监听查询参数变化，自动获取数据
  useEffect(() => {
    fetchUserList();
  }, [fetchUserList]);

  return (
    <>
      <Row>
        <Col>
          <SakuraSearchForm fields={formFields} onSearch={handleSearch} 
            onFieldClear={handleFieldClear}
          onReset={handleReset} />
        </Col>
      </Row>
      <IppeakTable
        loading={loading}
        dataSource={list}
        columns={columns}
        rowKey='index'
        tableHeight={320}
        selectedRowKeys={selectedRowKeys}
        onSelectChange={onSelectChange}
        pagination={{
          pageSize: query.page_size,
          total,
          current: query.page,
          showJumper: true,
          onCurrentChange: handleCurrentChange,
          onPageSizeChange: handlePageSizeChange,
        }}
      />
    </>
  );
};

const selectPage: React.FC = () => (
  <div className={classnames(CommonStyle.pageWithPadding, CommonStyle.pageWithColor)}>
    <SelectTable />
  </div>
);

export default memo(selectPage);
